package com.ouwen.smartpay.service.chain.slots.datas;

import com.fm.common.emuns.ResponseCode;
import com.fm.core.common.boot.Apps;
import com.fm.core.common.facade.BizResultBase;
import com.fm.core.common.facade.MerchOrderBase;
import com.fm.core.common.facade.MerchResultBase;
import com.fm.core.utils.Strings;
import com.ouwen.smartpay.entity.OrderDetail;
import com.ouwen.smartpay.entity.OrderInfo;
import com.ouwen.smartpay.openapi.order.ServiceOrder;
import com.ouwen.smartpay.service.OrderDetailService;
import com.ouwen.smartpay.service.OrderInfoService;
import com.ouwen.smartpay.service.chain.context.Context;
import com.ouwen.smartpay.service.chain.slotchain.AbstractLinkedProcessorSlot;
import com.ouwen.smartpay.service.chain.slots.SoltArgsToObjects;
import com.ouwen.smartpay.utils.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

/**
 * @author <a href="http://youngitman.tech">青年IT男</a>
 * @version v1.0.0
 * @className DatasSlot
 * @description 统一流水入库处理
 * @JunitTest: {@link  }
 * @date 2020-04-26 17:18
 **/
public class DatasSlot extends AbstractLinkedProcessorSlot<ServiceOrder> {

    Logger logger = LoggerFactory.getLogger(getClass());

    private OrderInfoService orderInfoService;

    private OrderDetailService orderDetailService;

    @Override
    public void entry(Context context, ServiceOrder serviceOrder, Object... args) throws Throwable {

        try {

            ApplicationContext applicationContext = Apps.getApplicationContext();

            orderInfoService = applicationContext.getBean(OrderInfoService.class);

            orderDetailService = applicationContext.getBean(OrderDetailService.class);

            //流水入库，前面处理幂等性这里可以直接入库
            MerchOrderBase order = context.getOrder();

            save(serviceOrder, order);

            fireEntry(context, serviceOrder, args);

        } catch (Exception e) {

            logger.error("数据流水持久化异常:", e);

            BizResultBase result = new BizResultBase();

            result.setRespCode(ResponseCode.FAIL.code());

            result.setRespMsg(ResponseCode.FAIL.message());

            result.setDescription(e.getMessage());

            exit(context, serviceOrder, args, result);

        }
    }

    @Override
    public void exit(Context context, Object... args) {

        //更新网关订单状态
        ServiceOrder order = SoltArgsToObjects.toServiceOrder(args);

        MerchResultBase merchResult = SoltArgsToObjects.toMerchResult(args);

        OrderInfo orderInfo = orderInfoService.findOrderInfoByPartnerIdAndAndSubParentIdRequestNo(order.getPartnerId(), order.getSubPartnerId(), order.getRequestNo());

        if (orderInfo != null) {

            orderInfo.setTranStatus(merchResult.getTranStatus());

            orderInfo.setTranDesc(merchResult.getTranDesc());

            orderInfo.setRespCode(merchResult.getRespCode());

            orderInfo.setRespMsg(merchResult.getRespMsg());

            if (Strings.isNoneBlank(merchResult.getDescription()) && merchResult.getDescription().length() > 1024) {

                orderInfo.setDescription(merchResult.getDescription().substring(0, 1024));

            } else {

                orderInfo.setDescription(merchResult.getDescription());

            }

            //orderInfo.setBizOrderNo(merchResult.get);

            orderInfo.setMerchOrderNo(merchResult.getMerchOrderNo());

            try {

                OrderDetail orderDetail = orderDetailService.findOrderDetailResponseInfoByOrderId(orderInfo.getId(), orderInfo.getPartnerId(), orderInfo.getSubPartnerId());

                //序列化结果
                String result = BeanUtil.mapToJson(BeanUtil.transBean2Map(merchResult));

                if (orderDetail == null) {

                    OrderDetail _orderDetail = new OrderDetail();

                    _orderDetail.setOrderId(orderInfo.getId());

                    _orderDetail.setResponseInfo(result);

                } else {

                    orderDetail.setResponseInfo(result);

                }

            } catch (Exception e) {

                //保证正常返回，通过人工数据订正
                logger.error("转换服务提供方结果报文异常:", e);
            }

            orderInfoService.update(orderInfo);

        }

        fireExit(context, args);

    }

    /***
     *
     * 保存流水信息
     *
     * @author liyong
     * @date 13:52 2020-04-26
     * @param serviceOrder
     * @param merchOrder
     * @exception
     * @return void
     **/
    private void save(ServiceOrder serviceOrder, MerchOrderBase merchOrder) {

        OrderInfoService orderInfoService = Apps.getApplicationContext().getBean(OrderInfoService.class);

        orderInfoService.saveOrderInfo(serviceOrder, merchOrder);

    }

}
